import datetime




#功能：生成日期列表
# 输入：开始 ，结束日期 '2021-05-06'
# 输出：日期 的  列表
def make_days_list(start,end):
    days=[]
    nowDay=start

    while nowDay!=end:
        days.append(nowDay.split('-'))
        nowDay= get_day_str(nowDay,1)

    days.append(end.split('-'))

    return days

# 获取日期字符串前后的，日期字符串
# str_time 格式 2021-05-26
def get_day_str(startDay,days):
    dd=datetime.datetime.strptime(startDay, "%Y-%m-%d")
    return (dd+datetime.timedelta(days=days)).strftime("%Y-%m-%d")


#功能：生成小时列表
# 输入：开始 ，结束小时 '2021-05-06 12:00:00'   '2021-05-08 12:00:00'
# 输出：小时 的  列表
def make_hours_list(start,end):
    hours=[]
    nowHour=start

    while nowHour!=end:

        oneList=[nowHour.split('-')[0],nowHour.split('-')[1],nowHour.split('-')[2][:2],nowHour.split('-')[2][3:5]]

        hours.append(oneList)
        nowHour= get_hour_str(nowHour,1)

    oneList = [end.split('-')[0], end.split('-')[1], end.split('-')[2][:2], end.split('-')[2][3:5]]
    hours.append(oneList)

    return hours

# 获取小时字符串前后的，小时字符串
# str_time 格式 2021-05-26 12:13:15
def get_hour_str(startHour,hours):
    dd=datetime.datetime.strptime(startHour, "%Y-%m-%d %H:%M:%S")
    return (dd+datetime.timedelta(hours=hours)).strftime("%Y-%m-%d %H:%M:%S")


# 为汇总函数准备数据，将每小时数据 里面，每个dataid 的最初，最末数据保留，并统计数据量。
def aggregate_prepare(dataHour):
    # 取平均值和数据数量
    # outData=inData.groupby('data_id').agg({'data_id':'max','data_value':'mean','data_time':'count'})
    dataCount = dataHour.groupby('data_id').agg({'data_id': 'max', 'data_time': 'count'})
    dataCount.rename(columns={"data_time": 'data_count'}, inplace=True)
    dataCount = dataCount.reset_index(drop=True)

    # dataCount.rename(columns={"data_value": 'data_mean',"data_time":"data_count"}, inplace=True)


    # 原始数据 按时间 排序
    dataHour = dataHour.sort_values(axis=0, ascending=True, by=['data_id','data_time'])
    # 必须重新设置索引
    dataHour = dataHour.reset_index(drop=True)

    # 期初一行  用copy 避免链式索引警告
    dataFirst=dataHour.drop_duplicates(['data_id'], keep='first',inplace=False).copy()
    # dataFirst = dataFirst.sort_values(axis=0, ascending=True, by=['data_id'])
    # dataFirst = dataFirst.reset_index(drop=True)

    # dataFirst.rename(columns={"data_value": 'data_first' }, inplace=True)

    # dataFirstOne=dataFirst[dataFirst['data_id']==2086563]

    # 期末值一行 用copy 避免链式索引警告
    dataLast = dataHour.drop_duplicates(['data_id'], keep='last',inplace=False).copy()
    # dataLast = dataLast.sort_values(axis=0, ascending=True, by=['data_id'])
    # dataLast = dataLast.reset_index(drop=True)
    # dataLast.drop(['data_time'], axis=1, inplace=True)
    # dataLast.rename(columns={"data_value": 'data_last'}, inplace=True)

    # dataLastOne = dataLast[dataLast['data_id'] == 2172275]

    # 期初 期末合并

    dataRes=dataLast.append(dataFirst)

    dataRes=dataRes.merge(dataCount, left_on='data_id', right_on='data_id')

    return dataRes





# 取前一天的
def get_y_m_d():
  # 计算前一天的年、月、日、时
  t = datetime.datetime.now() - datetime.timedelta(days=1)
  year = "%s"%(t.strftime("%Y"))
  month = "%s"%(t.strftime("%m"))
  day = "%s"%(t.strftime("%d"))

  print("%s  %s  %s"%(year, month, day))
  return  year, month, day

# 取前一小时的
def get_y_m_d_h():
  # 计算前一小时的年、月、日、时
  t = datetime.datetime.now() - datetime.timedelta(minutes=60)
  year = "%s" % (t.strftime("%Y"))
  month = "%s" % (t.strftime("%m"))
  day = "%s" % (t.strftime("%d"))
  hour = "%s" % (t.strftime("%H"))
  # print("-------------------------------------------------------------------")
  # print("task start at %s" % (datetime.now()))
  # print("%s  %s  %s  %s" % (year, month, day, hour))
  return year, month, day, hour

def make_file_name():
    target_time = datetime.datetime.now() + datetime.timedelta(hours=-1)
    csv_file_name = target_time.strftime("%Y/%m/%d/%H") + '/realtime-data-' + target_time.strftime(
        "%Y-%m-%d-%H") + '.csv'
    # print('make_file_name',csv_file_name)
    return csv_file_name